package com.teamcenter.rac.project.fragment.handlers;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.swing.text.StyledEditorKit.ForegroundAction;

import java.util.Map.Entry;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IWorkbenchPart;

import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.aif.AbstractAIFUIApplication;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.common.lov.view.controls.LOVDisplayer;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentFormType;
import com.teamcenter.rac.kernel.TCComponentGroup;
import com.teamcenter.rac.kernel.TCComponentGroupMember;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCComponentProcess;
import com.teamcenter.rac.kernel.TCComponentProcessType;
import com.teamcenter.rac.kernel.TCComponentProject;
import com.teamcenter.rac.kernel.TCComponentProjectType;
import com.teamcenter.rac.kernel.TCComponentQuery;
import com.teamcenter.rac.kernel.TCComponentQueryType;
import com.teamcenter.rac.kernel.TCComponentTaskTemplate;
import com.teamcenter.rac.kernel.TCComponentTaskTemplateType;
import com.teamcenter.rac.kernel.TCComponentType;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCPropertyDescriptor;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCTextService;
import com.teamcenter.rac.kernel.TCTypeService;
import com.teamcenter.rac.project.ProjectUtil;
import com.teamcenter.rac.project.common.IC_GroupRoleHashable;
import com.teamcenter.rac.project.common.IC_UserProxy;
import com.teamcenter.rac.project.common.ProjectConstants;
import com.teamcenter.rac.project.common.ProjectManager;
import com.teamcenter.rac.project.common.ProjectTeamTreeManager;
import com.teamcenter.rac.project.nodes.OrgTreeContentNode;
import com.teamcenter.rac.project.views.ProjectDefinitionView;
import com.teamcenter.rac.util.AdapterUtil;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.workflow.commands.newprocess.NewProcessCommand;
import com.teamcenter.rac.workflow.commands.newprocess.NewProcessDialog;
import com.teamcenter.services.internal.rac.core._2007_06.ProjectLevelSecurity;
import com.teamcenter.services.rac.core._2012_09.ProjectLevelSecurity.TeamMemberInfo;
import com.teamcenter.services.rac.core._2017_05.ProjectLevelSecurity.ProjectInformation2;

import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

public class MyProjectManager implements KeyListener, MouseListener, IPropertyChangeListener {

	public static final String PREFERENCE_NAME = "SIE_Project_Definition_Properties";
	public static final String RENAME_PROP_PREFERENCE_NAME = "SIE_Project_Definition_Rename_Properties";
	public static final String HIDE_PROP_PREFERENCE_NAME = "SIE_Project_Hide_Properties";
	public static Map<ProjectDefinitionView, MyProjectManager> PROJECT_DEFINITION_MANAGER_MAP = new HashMap<>();

	private ProjectDefinitionView projectDefinitionView;
	private Button submitButton;

	public static MyProjectManager getProjectManager(ProjectDefinitionView projectDefinitionView) {

		if (PROJECT_DEFINITION_MANAGER_MAP.containsKey(projectDefinitionView)) {
			return PROJECT_DEFINITION_MANAGER_MAP.get(projectDefinitionView);
		} else {
			MyProjectManager pm = new MyProjectManager(projectDefinitionView);
			PROJECT_DEFINITION_MANAGER_MAP.put(projectDefinitionView, pm);
			return pm;
		}
	}

	public static MyProjectManager getProjectManager() {
		return new MyProjectManager();
	}

	public static void injectManager() throws Exception {
		inject();
//		inject2();
		inject3();
		inject4();

	}

	public static void inject() throws Exception {

		ClassPool pool = ClassPool.getDefault();

		Class<?> cls = com.teamcenter.rac.project.plugin.Activator.class;

		ClassLoader loader = cls.getClassLoader();

		ClassClassPath cp = new ClassClassPath(cls);

		pool.insertClassPath(cp);

		pool.importPackage("java.util");
		pool.importPackage("com.teamcenter.rac.project.fragment.handlers.MyProjectManager");

		CtClass cc = pool.get("com.teamcenter.rac.project.views.ProjectDefinitionView");

		CtMethod ctMethod = cc.getDeclaredMethod("createTopForm",
				new CtClass[] { pool.get("org.eclipse.swt.widgets.Composite") });
		ctMethod.insertAfter("{MyProjectManager.getProjectManager(this).afterCreateTopForm($1);}");

		ctMethod = cc.getDeclaredMethod("processSetInput",
				new CtClass[] { pool.get("org.eclipse.ui.IWorkbenchPart"), pool.get("java.util.List") });
		ctMethod.insertAfter(
				"{MyProjectManager.getProjectManager(this).afterProcessSetInput($1, $2, m_projectTeamManager);}");

		// add a button :create a form and submit to workflow,cuichangbin
		ctMethod = cc.getDeclaredMethod("createButtons",
				new CtClass[] { pool.get("org.eclipse.swt.widgets.Composite") });
		ctMethod.insertAfter("{MyProjectManager.getProjectManager(this).createFormAndSubmitButton(this, $1);}");

		ctMethod = cc.getDeclaredMethod("validateButtons");
		ctMethod.insertAfter("{MyProjectManager.getProjectManager(this).afterValidateButtons();}");

		// 给每个方法注入一个标记
//		CtMethod[] methods = cc.getDeclaredMethods();
//		for (CtMethod ctMethod2 : methods) {
//			try {
//				System.out.println(ctMethod2.getName());
//				ctMethod2.insertAfter("{MyProjectManager.test(this, \"" + ctMethod2.getName() + "\");}");
//			}catch(Exception e) {
//				System.out.println(e.getMessage());
//			}
//			
//		}
		cc.toClass(loader, null);

	}

	public static void inject2() throws Exception {

		ClassPool pool = ClassPool.getDefault();

		Class<?> cls = com.teamcenter.rac.project.plugin.Activator.class;

		ClassLoader loader = cls.getClassLoader();

		ClassClassPath cp = new ClassClassPath(cls);

		pool.insertClassPath(cp);

		pool.importPackage("java.util");
		pool.importPackage("com.teamcenter.rac.project.fragment.handlers.MyProjectManager");

		CtClass cc = pool.get("com.teamcenter.rac.project.common.ProjectManager");

		CtMethod[] methods = cc.getDeclaredMethods();

		CtMethod ctMethod = null;

		for (CtMethod method : methods) {
			if (method.getName().equals("createProjects")) {
				ctMethod = method;
				break;
			}
		}

		ctMethod.insertBefore("{MyProjectManager.getProjectManager().beforeCreateProject($1,this);}");
		cc.toClass(loader, null);

	}

	public static void inject3() throws Exception {

		ClassPool pool = ClassPool.getDefault();

		Class<?> cls = com.teamcenter.rac.project.plugin.Activator.class;

		ClassLoader loader = cls.getClassLoader();

		ClassClassPath cp = new ClassClassPath(cls);

		pool.insertClassPath(cp);

		pool.importPackage("java.util");
		pool.importPackage("com.teamcenter.rac.project.fragment.handlers.MyProjectManager");

		CtClass cc = pool.get("com.teamcenter.rac.project.common.ProjectManager");

		CtMethod[] methods = cc.getDeclaredMethods();

		CtMethod ctMethod = null;

		for (CtMethod method : methods) {
			if (method.getName().equals("createProjects")) {
				ctMethod = method;
				break;
			}
		}

		ctMethod.insertAfter("{MyProjectManager.getProjectManager().afterCreateProject($1,this);}");
		cc.toClass(loader, null);

	}

	// add by cuichangbin,设置项目成员表单没有创建或没有发布，在项目定义界面不允许添加项目成员
	public static void inject4() throws Exception {

		ClassPool pool = ClassPool.getDefault();

		Class<?> cls = com.teamcenter.rac.project.plugin.Activator.class;

		ClassLoader loader = cls.getClassLoader();

		ClassClassPath cp = new ClassClassPath(cls);

		pool.insertClassPath(cp);

		pool.importPackage("java.util");
		pool.importPackage("com.teamcenter.rac.project.fragment.handlers.MyProjectManager");

		CtClass cc = pool.get("com.teamcenter.rac.project.common.ProjectTeamTreeManager");

		CtMethod[] methods = cc.getDeclaredMethods();

		CtMethod ctMethod = null;

		for (CtMethod method : methods) {
			if (method.getName().equals("addToSelectedMembersTree")) {
				ctMethod = method;
				break;
			}
		}

		ctMethod.insertBefore("{" + "if(!MyProjectManager.getProjectManager().beforeAddToSelectedMembersTree(this,$1)){"
				+ "	return;" + "}" + "}");
		cc.toClass(loader, null);

	}

	public boolean beforeAddToSelectedMembersTree(ProjectTeamTreeManager pttm, Tree paramTree) {
//		TCComponentProject project = pttm.getProject();

		TCSession session = (TCSession) AIFUtility.getDefaultSession();

		TreeItem[] sels = paramTree.getSelection();

		// 如果选择的是本人，则可以指派（因为创建项目必须要指派一个项目管理员）
		if (sels != null && sels.length == 1) {

			TreeItem sel = sels[0];

			Object selObj = sel.getData();

			if (selObj instanceof OrgTreeContentNode) {

				OrgTreeContentNode selNode = (OrgTreeContentNode) selObj;

				System.out.println(selNode.getObject().getClass());

				if (selNode.getObject() instanceof IC_UserProxy) {

					IC_UserProxy userProxy = (IC_UserProxy) selNode.getObject();

					if (session.getUser().equals(userProxy.getUser())) {
						return true;
					}

				}
			}

			System.out.println(sel.getData().getClass());
		}

		try {
			// 换成通过界面上填写的ProjectId来判断是否成员指派流程是否已发布
			ProjectDefinitionView projectDefinitionView = getValue(pttm, "m_projectDefinitionView");

			Text idText = getValue(projectDefinitionView, "m_idText");

			String projectId = idText.getText();

			TCComponentProject project = getProjectById(projectId);
			//项目创建时间早于2024-3-17（功能发布时间）不禁用
			SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
			Date effectDate=sdf1.parse("2024-03-17");
			Date proCreateDate=project.getDateProperty("creation_date");
			if (project == null || (!isCreateBeforeDate(proCreateDate,effectDate)&&!isAssignProjectMemberFormReleased(session, project.getProjectID()))) {
			// 未创建项目或者创建的项目对应的成员指派流程没有发布的情况下，限制添加成员
//			if (!isAssignProjectMemberFormReleased(session, projectId)) {
				MessageBox.post("项目没有完成设置项目成员审批流程，请先完成流程!", "禁止添加项目成员", MessageBox.ERROR);
				return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
			MessageBox.post(e, true);
			return false;
		}

		boolean isGroupOrRole = isGroupOrGroupRoleHashable(paramTree);

		if (!isGroupOrRole) {
			MessageDialog.openError(AIFUtility.getActiveDesktop().getShell(), "禁止添加部门或角色", "禁止添加部门或角色，请选择用户进行项目成员添加");
			return false;
		}

		return true;

	}
	public boolean isCreateBeforeDate(Date createDate,Date d) {
//		TCComponentProject selectPro=projectDefinitionView.getProject();
		try {
			if(createDate.before(d)) {
				return true; 
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return false;
	}
	public boolean isGroupOrGroupRoleHashable(Tree paramTree) {
		TreeItem[] arrayOfTreeItem = paramTree.getSelection();
//		boolean isGroupOrRole=false;
//		int treeItemCount=arrayOfTreeItem.length;
		for (int i = 0; i < arrayOfTreeItem.length; i++) {
			TreeItem treeItem = arrayOfTreeItem[i];
			if (treeItem.getData() instanceof OrgTreeContentNode) {
				OrgTreeContentNode orgTreeContentNode = (OrgTreeContentNode) treeItem.getData();
				Object object = orgTreeContentNode.getObject();
				if (object instanceof TCComponentGroup) {
					return false;
				} else if (object instanceof IC_GroupRoleHashable) {
					return false;
				}
			}
		}
		return true;
	}

	public TCComponentProject getProjectById(String projectId) throws TCException {

		TCSession session = (TCSession) AIFUtility.getDefaultSession();

		TCComponentProjectType projectType = (TCComponentProjectType) session.getTypeComponent("TC_Project");

		return projectType.find(projectId);

	}

	public boolean isAssignProjectMemberFormReleased(TCSession session, String selectProjectID) throws TCException {
		boolean isReleased = false;
		TCComponentQueryType querytype = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
		String queryName = "P8_AssignProjectMemberForm";
		TCComponentQuery query = (TCComponentQuery) querytype.find(queryName);
		querytype.clearCache();
		if (query == null)
			throw new RuntimeException("未定义的查询[" + queryName + "]");

		String[] keytexts = new String[2];
		keytexts[0] = "Projects";
		keytexts[1] = "is_summary";
		String[] valuetexts = new String[2];
		valuetexts[0] = selectProjectID;
		valuetexts[1] = "TRUE";
		TCComponent[] results = query.execute(keytexts, valuetexts);
		query.clearCache();
		for (TCComponent AssignPMemberForm : results) {
//	    	  System.out.println(AssignPMemberForm.getTypeComponent().toDisplayString());
			if (AssignPMemberForm.getTypeComponent().toString().equals("P8_AssignPMemberForm")) {
				TCComponent[] statuses = AssignPMemberForm.getReferenceListProperty("release_status_list");
				for (TCComponent status : statuses) {
					if (status != null) {
						if (status.toString().equals("发布")) {
							isReleased = true;
						}
					}
				}
			}
		}
		return isReleased;
	}

	public String AssignPMemberFormInProcess(TCSession session, String selectProjectID) throws Exception {
		boolean isReleased = false;
		String processStr = null;
		TCComponent[] results = queryAssignProjectTeamMember(session, selectProjectID);
		for (TCComponent AssignPMemberForm : results) {
//	    	  System.out.println(AssignPMemberForm.getTypeComponent().toDisplayString());
			if (AssignPMemberForm.getTypeComponent().toString().equals("P8_AssignPMemberForm")) {
				TCComponent[] statuses = AssignPMemberForm.getReferenceListProperty("release_status_list");
				TCComponent[] process=AssignPMemberForm.getReferenceListProperty("process_stage_list");;
				
				for (TCComponent status : statuses) {
					if (status != null) {
						if (status.toString().equals("发布")) {
							isReleased = true;
							break;
						}
					}
				}
				if (isReleased) {
					break;
				}else if(process !=null&&process.length > 0) {
					processStr = "项目成员一览表未发布，先发布";
					break;
				}
			}
		}
		if (isReleased) {
			processStr = "项目成员一览表已发布,不用再发起流程";
		} 
		return processStr;
	}

	public void createFormAndSubmitButton(ProjectDefinitionView projectDefinitionView, Composite var1) {
//		System.out.println("run createFormAndSubmitButton");
		this.submitButton = null;
		try {
			this.submitButton = projectDefinitionView.getToolkit().createButton(var1, "创建项目成员设置流程", 8);
			this.submitButton.setToolTipText("创建项目成员设置流程");
			this.submitButton.addSelectionListener(new SelectionListener() {
				public void widgetSelected(SelectionEvent param1SelectionEvent) {
					if (projectDefinitionView.getProject() == null) {
						MessageDialog.openError(AIFUtility.getActiveDesktop().getShell(), "请选择项目", "请选择项目发起项目成员设置流程");
						return;
					}
					try {
						String inprocessmsg = AssignPMemberFormInProcess((TCSession) AIFUtility.getDefaultSession(),
								projectDefinitionView.getProject().getProjectID());
						if(inprocessmsg == null) {
							System.out.println( inprocessmsg + "为空");
						}
						if (inprocessmsg!=null && inprocessmsg.equals("项目成员一览表已发布,不用再发起流程")) {
							MessageDialog.openError(AIFUtility.getActiveDesktop().getShell(), "请勿重复发起流程",
									"已完成项目成员设置流程");
							return;
						} else if (inprocessmsg!=null && inprocessmsg.equals("项目成员一览表未发布，先发布")) {
							MessageDialog.openError(AIFUtility.getActiveDesktop().getShell(), "请勿重复发起流程",
									"已发起过项目成员设置流程，正在流程中");
							return;
						}else {
							if (!MessageDialog.openConfirm(AIFUtility.getActiveDesktop().getShell(), "提示",
									"是否立即发起项目成员指派流程?")) {
								return;
							}
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					try {
//						List<String> ids = new ArrayList<>();
						TCComponentProject tCComponentProject = projectDefinitionView.getProject();
						String[] porjids = new String[1];
						porjids[0] = tCComponentProject.getProjectID();
						
						// 获取项目名 
						String prpjectName = tCComponentProject.getProjectName();
//						String[] proNames = new String[1];
//						proNames[0] = prpjectName;
						TCComponentForm form = createProjectMemberAssignSummaryForm(porjids,prpjectName);

						AbstractAIFUIApplication app = AIFUtility.getCurrentApplication();

						NewProcessCommand newProcessCommand = new NewProcessCommand(AIFUtility.getActiveDesktop(), app,
								new TCComponentForm[] { form });

						newProcessCommand.executeModal();

					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				public void widgetDefaultSelected(SelectionEvent param1SelectionEvent) {
				}
			});
			if (projectDefinitionView.getProject() == null)
				submitButton.setEnabled(false);
//			Control[] controls = var1.getChildren();
//			
//			Composite composite = (Composite)controls[0];

		} catch (Exception ex) {

		}

	}
	public TCComponent[] queryAssignProjectTeamMember(TCSession session,String selectProjectID) {
		
		try {
			TCComponentQueryType querytype = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
			String queryName = "P8_AssignProjectMemberForm";
			TCComponentQuery query = (TCComponentQuery) querytype.find(queryName);
			querytype.clearCache();
			if (query == null)
				throw new RuntimeException("未定义的查询[" + queryName + "]");

			String[] keytexts = new String[2];
			keytexts[0] = "Projects";
			keytexts[1] = "is_summary";
			String[] valuetexts = new String[2];
			valuetexts[0] = selectProjectID;
			valuetexts[1] = "TRUE";
			TCComponent[] results = query.execute(keytexts, valuetexts);
			query.clearCache();
			return results;
		} catch (TCException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}
	public void beforeCreateProject(ProjectInformation2[] paramArrayOfProjectInformation2) {
		System.out.println("beforeCreateProject...");
		for (ProjectInformation2 projectInformation2 : paramArrayOfProjectInformation2) {
			System.out.println(projectInformation2);
			for (Entry<String, String[]> entry : projectInformation2.propertyMap.entrySet()) {
				System.out.println("prop name : " + entry.getKey());
				for (String str : entry.getValue()) {
					System.out.println(" -->" + str);
				}
			}
			projectInformation2.propertyMap.put("p8_niandu_lc", new String[] { "2" });
		}
	}

	public void afterCreateProject(ProjectInformation2[] projInfos, ProjectManager pm) throws TCException {
		Display.getDefault().asyncExec(new Runnable() {
			@Override
			public void run() {
				// 在 UI 线程上执行的代码块
				// 可以在这里进行 UI 相关操作
				// 例如更新 UI 元素、显示对话框等
				// 提示是否需要立即指派
				if (!MessageDialog.openConfirm(AIFUtility.getActiveDesktop().getShell(), "提示", "是否立即发起项目成员指派流程?")) {
					return;
				}

				try {
					List<String> ids = new ArrayList<>();
//					List<String> names = new ArrayList<>();
					String projectName = "";
					for (ProjectInformation2 projInfo : projInfos) {
						ids.add(projInfo.projectId);
						projectName = projInfo.projectName;
					}
					String[] projids = ids.toArray(ids.toArray(new String[ids.size()]));
//					String[] proNames = names.toArray(names.toArray(new String[names.size()]));
					TCComponentForm form = createProjectMemberAssignSummaryForm(projids,projectName);

					AbstractAIFUIApplication app = AIFUtility.getCurrentApplication();

					NewProcessCommand newProcessCommand = new NewProcessCommand(AIFUtility.getActiveDesktop(), app,
							new TCComponentForm[] { form });

					newProcessCommand.executeModal();

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

	}

	public TCComponentForm createProjectMemberAssignSummaryForm(String[] projectids,String projectName) throws Exception {
		TCComponentForm teamUserForm=null;
		TCSession session = (TCSession) AIFUtility.getDefaultSession();
		TCComponent[] result= queryAssignProjectTeamMember(session, projectids[0]);
		if(result!=null && result.length>0) {
			teamUserForm=(TCComponentForm) result[0];
		}else {

			TCComponentFormType prjMemberFormType = (TCComponentFormType) session.getTypeComponent("P8_AssignPMemberForm");
	
			teamUserForm = prjMemberFormType.create("项目成员一览表（汇总）", "项目成员", "P8_AssignPMemberForm");
	
			TCProperty tcp = teamUserForm.getTCProperty("p8_Projects");
	
			if (tcp != null) {
				if (projectids != null)
					tcp.setStringValueArray(projectids);
					teamUserForm.setLogicalProperty("p8_is_summary", true);
					teamUserForm.setStringProperty("p8_ProjectName", projectName);
			}
			
//			TCProperty tcp2 = teamUserForm.getTCProperty("p8_ProjectName");
//			
//			if(tcp2 != null ) {
//				if(projectName != null) {
//					tcp.setStringValue(projectName);
//				}
//			}
			
		}

		return teamUserForm;
	}

//	public TCComponentForm createProjectMemberAssignSummaryForm(ProjectInformation2[] projInfos) throws Exception {
//		
//		TCSession session = (TCSession) AIFUtility.getDefaultSession();
//		
//		TCComponentFormType prjMemberFormType =(TCComponentFormType)session.getTypeComponent("P8_AssignPMemberForm");
//		
//		TCComponentForm teamUserForm = prjMemberFormType.create("项目成员一览表（汇总）", "项目成员", "P8_AssignPMemberForm");
//		
//		TCProperty tcp = teamUserForm.getTCProperty("p8_Projects");
//		
//		List<String> ids = new ArrayList<>();
//		
//		for (ProjectInformation2 projInfo : projInfos) {
//			ids.add(projInfo.projectId);
//		}
//		
//		String idComb = String.join(",", ids);
//		
//		if (tcp != null) {
//			tcp.setStringValueArray(ids.toArray(new String[ids.size()]));
//			teamUserForm.setLogicalProperty("p8_is_summary", true);
//		}
//		
//		return teamUserForm;
//	}

	/**
	 * Created by CuiChangbing 20240304
	 * 
	 * @param paramArrayOfProjectInformation2
	 * @param pm
	 * @throws TCException
	 */
	public void afterCreateProject2(ProjectInformation2[] paramArrayOfProjectInformation2, ProjectManager pm)
			throws TCException {

		System.out.println("beforeCreateProject...");
		List<TCComponentProject> projects = pm.getProjects();
		TCComponentProject createproj = null;
		TCSession session = (TCSession) AIFUtility.getDefaultSession();
		TCComponentFormType prjMemberForm = (TCComponentFormType) session.getTypeComponent("P8AssignPMemberForm");
		TCTypeService service = session.getTypeService();
		TCComponentProjectType pt = (TCComponentProjectType) service.getTypeComponent("TC_Project");

		List<TCComponentForm> teamUserForms = new ArrayList<TCComponentForm>();
//		Vector<TCComponent> vec = new Vector<TCComponent>();
		for (ProjectInformation2 projectInformation2 : paramArrayOfProjectInformation2) {
//			
//			projectInformation2.
			String pId = projectInformation2.projectId;
			System.out.println(pId);
//			for (Entry<String, String[]> entry : projectInformation2.propertyMap.entrySet()) {
//				System.out.println("prop name : " + entry.getKey());
//				for (String str : entry.getValue()) {
//					System.out.println( " -->" + str);
//				}
//			}
//			if(projects!=null && !pId.isEmpty()) {
//				for (TCComponentProject project : projects) {
//					System.out.println(project.getProjectID());
//					System.out.println(project.getProjectID()==pId);
//					if(project.getProjectID()==pId){
//						createproj=project;
//					}
//				}
//			}
			for (TeamMemberInfo teami : projectInformation2.teamMembers) {
				System.out.println(teami.teamMember.toString());
				if (teami.teamMember instanceof TCComponentUser) {
					System.out.println(teami.toString());
					if (teami.teamMemberType == 2) {
						TCComponentUser teamUser = (TCComponentUser) teami.teamMember;
						// 名稱，描述，類型
						TCComponentForm teamUserForm = prjMemberForm.create(teamUser.getUserName() + "-項目成員表單", "項目成員",
								"P8AssignPMemberForm");
						TCProperty tcp = teamUserForm.getTCProperty("p8Projects");
						if (tcp != null) {
//							System.out.println(project.getProjectID());
							List<String> porjectids = new ArrayList<String>();
							porjectids.add(pId);
							tcp.setStringValueArray(porjectids.toArray(new String[porjectids.size()]));
						}
						teamUserForm.setStringProperty("p8_ProjectName", projectInformation2.projectName);
						if (createproj != null)
							pt.assignToProject(createproj, teamUserForm);
						teamUserForm.changeOwner(teamUser, teamUser.getLoginGroup());
						teamUserForms.add(teamUserForm);
//						TCComponentItemType it=(TCComponentItemType) session.getTypeComponent("Item");
//						String id = it.getNewID();
//						TCComponentItem item1=it.create(id, "A", "Item", "test add to workflow", "", null);
//						vec.add(teamUserForm);
					}
				}
			}
//			teami.
			projectInformation2.propertyMap.put("p8_niandu_lc", new String[] { "2" });
		}
		if (teamUserForms != null || teamUserForms.size() > 0) {

			try {
//		      TCComponentProcessType TCComponentProcessType = (TCComponentProcessType)session.getTypeComponent("EPMJob");
//		      TCComponentTaskTemplateType ttt=(TCComponentTaskTemplateType) session.getTypeComponent("");
				AbstractAIFUIApplication application = AIFUtility.getCurrentApplication();
//				teamUserForms.toArray(new TCComponent[vec.size()]);
				AIFDesktop dtop = AIFUtility.getActiveDesktop();
				System.out.println(dtop.toString());
				System.out.println(application.toString());
				InterfaceAIFComponent[] comps = application.getTargetComponents();
				System.out.println(comps.length);

//				 AbstractTCCommandDialog abstractTCCommandDialog = (AbstractTCCommandDialog)registry.newInstanceFor("newProcessDialog", new Object[] { this.this$0 });            
//				NewProcessCommand newProcessCommand = new NewProcessCommand(AIFUtility.getActiveDesktop(), application,
//						teamUserForms.toArray(new TCComponent[teamUserForms.size()]));

//				NewProcessDialog newProcessDialog = new NewProcessDialog(null);

//				newProcessDialog.processDefinitionComboBox.addItem("aaaaaaa");
//				newProcessDialog.setTitle("sssss");

//				Method method = newProcessCommand.getClass().getMethod("setRunnable", Runnable.class);
//				method.setAccessible(true);
//				method.invoke(newProcessCommand, newProcessDialog);

//				newProcessCommand.executeModal();

//				newProcessDialog.setVisible(true);
//		      ttt.c
//		      TCComponentProcess pp=(TCComponentProcess) TCComponentProcessType.create("proceesname", "proceesdesc", new TCComponentTaskTemplate());
//		      TCComponentProcessType.create("", "", teamUserForms, null, null);
			} catch (Exception localException2) {

				return;
			}
		}

	}

	public static void test(Object obj, String str) {
		System.out.println(obj.getClass() + " : " + str);
	}

	private Map<String, Control> propertiesMap = new HashMap<>();
	private Map<String, Control> mandatoryPropertiesMap = new HashMap<>();

	public MyProjectManager() {

	}

	public MyProjectManager(ProjectDefinitionView projectDefinitionView) {
		this.projectDefinitionView = projectDefinitionView;
		try {
			// 创建和修改后操作在projectUIPostActions类中
			setValue(projectDefinitionView, "projectUIPostActions", new MyProjectUIPostActions(this));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setValue(Object obj, String name, Object value) throws Exception {
		Field field = obj.getClass().getDeclaredField(name);
		field.setAccessible(true);
		field.set(obj, value);
	}

	@SuppressWarnings("unchecked")
	public <T> T getValue(Object obj, String name) throws Exception {
		Field field = obj.getClass().getDeclaredField(name);
		field.setAccessible(true);
		return (T) field.get(obj);

	}

	static void access$7(final ProjectDefinitionView projectDefinitionView, final boolean isDirty) throws Exception {
		Field field = projectDefinitionView.getClass().getDeclaredField("isDirty");
		field.setAccessible(true);
		field.set(projectDefinitionView, isDirty);
	}

	public void afterProcessSetInput(final IWorkbenchPart workbenchPart, final List<Object> list,
			ProjectTeamTreeManager projectTeamManager) {

		final Object o = list.isEmpty() ? null : list.get(0);

		TCComponentProject project = (TCComponentProject) AdapterUtil.getAdapter(o, TCComponentProject.class, true);

		try {

			loadSpecProperteies(project);
			
			project = projectTeamManager.getProject();
			
			if(project != null)return;

			TCSession session = (TCSession) AIFUtility.getDefaultSession();

			new Thread() {
				public void run() {
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					Display.getDefault().asyncExec(() -> {
						projectTeamManager.addAsAdmin(session.getGroup(), session.getRole(), session.getUser());
					});
				}
			}.start();

//			projectTeamManager.get

		} catch (TCException e) {
			e.printStackTrace();
			MessageBox.post(e);
		}
	}

	public void afterCreateTopForm(Composite var1) {

		try {

			Control[] controls = var1.getChildren();

			Composite composite = (Composite) controls[0];

			String[] hideProperties = getConfigHideProperties();

			if (hideProperties != null && hideProperties.length > 0) {

				List<String> hidePropList = new ArrayList<String>(Arrays.asList(hideProperties));

				Control[] childControls = composite.getChildren();

				// 隐藏指定的属性
				for (int i = 0; i < childControls.length; i++) {

					if (!childControls[i].isDisposed() && childControls[i] instanceof Label) {
						if (hidePropList.contains(((Label) childControls[i]).getText())) {
							childControls[i].dispose();
							for (i = i + 1; i < childControls.length; i++) {
								if (childControls[i] instanceof Label) {
									Label lb = (Label) childControls[i];
									String lbt = lb.getText();
									if (lbt != null && !lbt.equals("*") && !lbt.trim().isEmpty()) {
										break;
									}
									childControls[i].dispose();
								}
								childControls[i].dispose();
							}
						}
					}

				}
			}

			// 替换属性名的属性
			Map<String, String> renameProperties = getRenameProperties();
			if (renameProperties != null && renameProperties.size() > 0) {

				Control[] childControls = composite.getChildren();

				// 隐藏指定的属性
				for (int i = 0; i < childControls.length; i++) {

					if (!childControls[i].isDisposed() && childControls[i] instanceof Label) {

						Label label = (Label) childControls[i];
						String name = label.getText();
						if (renameProperties.containsKey(name)) {
							label.setText(renameProperties.get(name));
						}
					}

				}
			}

			// 新增的属性
			String[] configProperties = getConfigProperties();
			if (configProperties == null || configProperties.length == 0)
				return;

			TCComponentType projectType = projectDefinitionView.getTCSession().getTypeComponent("TC_Project");
			TCComponentProject project = getValue(projectDefinitionView, "project");

			for (int i = 0; i < configProperties.length; i++) {

				String configProperty = configProperties[i];
				boolean mandatory = false;
				if (configProperty.startsWith("*")) {
					configProperty = configProperty.substring(1, configProperty.length());
					mandatory = true;
				}
				TCPropertyDescriptor propDesc = projectType.getPropertyDescriptor(configProperty);
				if (propDesc == null) {
					continue;
				}

				Label nameLabel = projectDefinitionView.getToolkit().createLabel(composite, propDesc.getDisplayName());
				Label mandaryLabel = null;
				if (mandatory) {
					mandaryLabel = projectDefinitionView.getToolkit().createLabel(composite, "*");
					mandaryLabel.setForeground(composite.getDisplay().getSystemColor(3));
				} else {
					mandaryLabel = projectDefinitionView.getToolkit().createLabel(composite, "");
				}
				GridData var11 = new GridData(4, 4, false, false);
				mandaryLabel.setLayoutData(var11);
				int propType = propDesc.getType();
				Control propControl = null;
				if (propDesc.hasLOVAttached()) {
					LOVDisplayer lovDisplay = new LOVDisplayer(composite, 4);
					lovDisplay.initialize(project, propDesc, (Object) null);
					projectDefinitionView.getToolkit().adapt(lovDisplay, true, true);
					propControl = lovDisplay;
					lovDisplay.addPropertyChangeListener(this);
				} else if (propType == TCProperty.PROP_logical) {
					LogicalRadioGroup radioGroup = new LogicalRadioGroup(composite, 4, configProperty);
					propControl = radioGroup;
					radioGroup.addPropertyChangeListener(this);
				} else {
					Text text = projectDefinitionView.getToolkit().createText(composite, "", 2626);
					projectDefinitionView.getToolkit().adapt(text, true, true);
					propControl = text;
					text.addKeyListener(this);
					text.addMouseListener(this);
				}
				propertiesMap.put(configProperty, propControl);
				if (mandatory) {
					mandatoryPropertiesMap.put(configProperty, propControl);
				}

				GridData var8 = new GridData(16384, 16777216, true, false);
				var8.widthHint = 250;
				var8.heightHint = 25;
				propControl.setLayoutData(var8);
			}

			// 加个空格控件
			projectDefinitionView.getToolkit().createLabel(composite, "");

			Button m_activeStatusBtn = getValue(projectDefinitionView, "m_activeStatusBtn");
			Button m_inactiveStatusBtn = getValue(projectDefinitionView, "m_inactiveStatusBtn");
			Button m_inactiveandInviisibleStatusBtn = getValue(projectDefinitionView,
					"m_inactiveandInviisibleStatusBtn");

			m_activeStatusBtn.setText("正常");
			m_inactiveStatusBtn.setText("暂停");
			m_inactiveandInviisibleStatusBtn.setText("取消");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void afterValidateButtons() {
		try {
			Button button2 = getValue(this, "submitButton");
			TCComponentProject project = projectDefinitionView.getProject();
			if (project == null) {
				button2.setEnabled(false);
				return;
			}

			boolean hasModified = false;

//			getProjectManager();

//			System.out.println("button2 is "+button2.toString());
			button2.setEnabled(true);
			for (Entry<String, Control> entry : propertiesMap.entrySet()) {

				String proValue = project.getProperty(entry.getKey());
				String inputValue = getControlValue(entry.getValue());

				if (!inputValue.equals(proValue)) {
					hasModified = true;
					break;
				}
			}
			if (hasModified) {
				Button button = getValue(projectDefinitionView, "m_modifyButton");
				button.setEnabled(true);
			}

			boolean hasNullMandatory = false;
			// 必填项不得为空
			for (Entry<String, Control> entry : mandatoryPropertiesMap.entrySet()) {
				String inputValue = getControlValue(entry.getValue());
				if (inputValue == null || inputValue.isEmpty()) {
					hasNullMandatory = true;
					break;
				}
			}
			if (hasNullMandatory) {
				projectDefinitionView.disableButtons();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	public void loadSpecProperteies(TCComponentProject project) throws TCException {
		if (project == null)
			return;
		for (Entry<String, Control> entry : propertiesMap.entrySet()) {
			String propName = entry.getKey();
			String value = project.getProperty(propName);
			setControlValue(entry.getValue(), value);
		}
	}

	public void saveSpecProperties(TCComponentProject project) throws Exception {
		if (propertiesMap.size() == 0)
			return;

		final Map<String, String> props = new HashMap<>();

		Display.getDefault().asyncExec(new Runnable() {
			@Override
			public void run() {
				for (Entry<String, Control> entry : propertiesMap.entrySet()) {
					String propName = entry.getKey();
					String value = getControlValue(entry.getValue());
					props.put(propName, value);
//					project.setProperty(propName, value);
				}
			}
		});

		while (props.size() < propertiesMap.size()) {
			Thread.sleep(100);
		}

		project.setProperties(props);
	}

	public String getControlValue(Control control) {
		if (control == null)
			return null;
		if (control instanceof Text) {
			return ((Text) control).getText();
		} else if (control instanceof LOVDisplayer) {
			return (String) ((LOVDisplayer) control).getSelectedValue();
		} else if (control instanceof LogicalRadioGroup) {
			return ((LogicalRadioGroup) control).getDisplableValue();
		} else {
			return "";
		}
	}

	public void setControlValue(Control control, String text) {
		if (control == null)
			return;
		if (control instanceof Text) {
			((Text) control).setText(text);
		} else if (control instanceof LOVDisplayer) {
			((LOVDisplayer) control).setSelectedValue(text);
		} else if (control instanceof LogicalRadioGroup) {
			boolean flag = text != null && text.length() > 0 && (text.equals("Y") || text.equals("true"));
			((LogicalRadioGroup) control).setValue(flag);
		}
	}

	public String[] getConfigProperties() {
		TCSession session = (TCSession) AIFUtility.getDefaultSession();
		return session.getPreferenceService().getStringValues(PREFERENCE_NAME);
	}

	public String[] getConfigHideProperties() {
		TCSession session = (TCSession) AIFUtility.getDefaultSession();
		return session.getPreferenceService().getStringValues(HIDE_PROP_PREFERENCE_NAME);
	}

	public Map<String, String> getRenameProperties() {
		TCSession session = (TCSession) AIFUtility.getDefaultSession();
		String[] strs = session.getPreferenceService().getStringValues(RENAME_PROP_PREFERENCE_NAME);
		Map<String, String> map = new HashMap<>();
		if (strs != null && strs.length > 0) {
			for (String string : strs) {
				if (string.contains("=")) {
					String[] spits = string.split("=");
					map.put(spits[0], spits[1]);
				}
			}
		}

		return map;
	}

	public void keyReleased(final KeyEvent keyEvent) {
		try {
			if ((boolean) getValue(projectDefinitionView, "isPA") || (boolean) getValue(projectDefinitionView, "isPTA")
					|| projectDefinitionView.isPTA()) {
				projectDefinitionView.validateButtons();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void keyPressed(final KeyEvent keyEvent) {
		try {
			access$7(projectDefinitionView, true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void mouseMove(final MouseEvent mouseEvent) {
		if (mouseEvent.widget instanceof Text) {
			Text text = (Text) mouseEvent.widget;
			if (text.getCharCount() > 50) {
				text.setToolTipText(text.getText());
			} else {
				text.setToolTipText("");
			}
		}
	}

	public void propertyChange(final PropertyChangeEvent propertyChangeEvent) {
		try {
			boolean isPA = getValue(projectDefinitionView, "isPA");
			boolean isPTA = getValue(projectDefinitionView, "isPTA");
			if (isPA || isPTA || projectDefinitionView.isPTA()) {
				projectDefinitionView.validateButtons();
				access$7(projectDefinitionView, true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void mouseDoubleClick(MouseEvent var1) {

	}

	@Override
	public void mouseDown(MouseEvent var1) {

	}

	@Override
	public void mouseUp(MouseEvent var1) {

	}

}
